home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / zip.zip / IM_LMAT.C < prev    next >
C/C++ Source or Header  |  1992-09-22  |  28KB  |  726 lines

  1. /*
  2.  
  3.  Copyright (C) 1990,1991 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
  4.  Permission is granted to any individual or institution to use, copy, or
  5.  redistribute this software so long as all of the original files are included
  6.  unmodified, that it is not sold for profit, and that this copyright notice
  7.  is retained.
  8.  
  9. */
  10.  
  11. /*
  12.  *  im_lmat.c by Jean-loup Gailly.
  13.  *
  14.  *  PURPOSE
  15.  *
  16.  *      Identify new text as repetitions of old text within a fixed-
  17.  *      length sliding window trailing behind the new text.
  18.  *
  19.  *  DISCUSSION
  20.  *
  21.  *      The "implosion" process depends on being able to identify portions
  22.  *      of the input text which are identical to earlier input (within a
  23.  *      sliding window trailing behind the input currently being processed).
  24.  *
  25.  *      The most straightforward technique turns out to be the fastest for
  26.  *      most input files: try all possible matches and select the longest.
  27.  *      The key feature is of this algorithm is that insertion and deletions
  28.  *      from the string dictionary are very simple and thus fast. Insertions
  29.  *      and deletions are performed at each input character, whereas string
  30.  *      matches are performed only when the previous match ends. So it is
  31.  *      preferable to spend more time in matches to allow very fast string
  32.  *      insertions and deletions. The matching algorithm for small strings
  33.  *      is inspired from that of Rabin & Karp. A brute force approach is
  34.  *      used to find longer strings when a small match has been found.
  35.  *      A similar algorithm is used in freeze (by Leonid Broukhis) but the
  36.  *      algorithm used here is faster.
  37.  *         A previous version of this file used a more sophisticated algorithm
  38.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  39.  *      time, but has a larger average cost and uses more memory. However
  40.  *      the F&G algorithm may be faster for some highly redundant files if
  41.  *      the parameter max_chain_length (described below) is too large.
  42.  *
  43.  *  ACKNOWLEDGEMENTS
  44.  *
  45.  *      Rich Wales defined the interface, provided the necessary information
  46.  *      to ensure compatibility with pkunzip 1.0 (not an easy job) and
  47.  *      suggested the solution (n == 1 + n-1) adopted here.
  48.  *      The idea of lazy evaluation of matches is due to Jan Mark Wams, and
  49.  *      I found it in 'freeze' written by Leonid Broukhis.
  50.  *      Special thanks to Kai-Uwe Rommel for the OS/2 port, to Glenn J.
  51.  *      Andrews for the VMS port, and to many other info-zippers for testing.
  52.  *
  53.  *  REFERENCES
  54.  *
  55.  *      A description of the Rabin and Karp algorithm is given in the book
  56.  *          "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  57.  *
  58.  *      Fiala,E.R., and Greene,D.H.
  59.  *          Data Compression with Finite Windows, CACM, 32,4 (1989) 490-595.
  60.  *
  61.  *  INTERFACE
  62.  *
  63.  *      ImpErr lm_init (int pack_level)
  64.  *          Initialize the "longest match" routines for a new file.
  65.  *          The global variable fd is an implicit parameter.
  66.  *
  67.  *      ImpErr lm_input (U_CHAR *block, U_INT count)
  68.  *          Process a block of input characters.
  69.  *
  70.  *      ImpErr lm_windup (void)
  71.  *          Flush out the remaining unprocessed input.
  72.  */
  73.  
  74. #include "implode.h"
  75.  
  76. /***********************************************************************
  77.  *
  78.  * Configuration parameters
  79.  */
  80.  
  81. #define MAX_MATCH_LENGTH  320
  82. /* The maximum match length. 320 = 64 + 256. (If the length is greater than
  83.  * 63, pkzip uses an extra byte.)
  84.  */
  85.  
  86. #define MAX_WBITS  13
  87. #define WSIZE (1 << MAX_WBITS)
  88. /* Maximum window size = 8K */
  89.  
  90. /* Constants used to dimension the hash table: */
  91. #define HASH_BITS  14
  92. /* HASH_BITS must be >= 13, see longest_match() */
  93.  
  94. #define HASH_SIZE (1<<HASH_BITS)
  95. #define HASH_MASK (HASH_SIZE-1)
  96.  
  97. #if defined(MSDOS) || defined(i386) || defined(mc68020) || defined(vax)
  98. #   define UNALIGNED_OK
  99.     /* Define this symbol if your target allows access to unaligned data.
  100.      * This is not mandatory, just a speed optimization. The compressed
  101.      * output is strictly identical.
  102.      */
  103. #endif
  104. #ifdef __TURBOC__
  105. #   define DYN_ALLOC
  106.     /* Turbo C 2.0 does not accept far static allocations in small model */
  107. #endif
  108.  
  109. /***********************************************************************
  110.  *
  111.  * Local data used by the "longest match" routines.
  112.  */
  113.  
  114. #if HASH_BITS <= 14
  115.    typedef unsigned short Hash;
  116. #else
  117.    /* Defined just for safety, since values > 14 do not speed up implosion */
  118.    typedef unsigned long Hash;
  119. #endif
  120.  
  121. typedef unsigned short Pos;
  122. typedef unsigned int  IPos;
  123. /* A Pos is an index in the character window. We use short instead of int to
  124.  * save space in the various tables. IPos is used only for parameter passing.
  125.  */
  126.  
  127. int near min_match_length;
  128. /* Minimum match length, 2 for binary files, 3 for ascii files.
  129.  * (bad luck for ebcdic users; not because they may not get optimal
  130.  * compression, but because they have to use ebcdic machines :-)
  131.  * A zero value means that the min_match_length is not yet determined.
  132.  */
  133.  
  134. U_CHAR near window[MAX_MATCH_LENGTH + WSIZE + BSZ];
  135. /* MAX_MATCH_LENGTH bytes are duplicated at both ends of the window,
  136.  * to speed up string comparisons. The BSZ extra bytes allow a block copy
  137.  * of the input buffer into the window instead of a copy one byte at a time.
  138.  */
  139.  
  140. #define MAX_DIST (WSIZE + BSZ)
  141. /* Maximum theoretical distance between two distinct bytes in the window.
  142.  * Actual distances are limited to bufsize.
  143.  */
  144.  
  145. #define NIL  MAX_DIST
  146. /* Tail of hash chains */
  147.  
  148. #ifdef DYN_ALLOC
  149.    Hash far *next = NULL;
  150.    Pos  far *prev = NULL;
  151. #else
  152.    Hash far next[MAX_DIST+1];
  153.    Pos  far prev[MAX_DIST+HASH_SIZE+1];
  154. #endif
  155. /* next is a link to a more recent string with same hash index, or to the head
  156.  * of a hash table chain if there is no such string. next[NIL] is used to
  157.  * avoid extra checks. next[s] is NIL if string s is not yet in the dictionary
  158.  *
  159.  * prev is a link to an older string with same hash index (first MAX_DIST
  160.  * values) or head of hash chain (last HASH_SIZE values). prev[NIL] is used
  161.  * to avoid extra checks.
  162.  */
  163. #define match_head (prev+(MAX_DIST+1))
  164.  
  165. Hash near ins_h;  /* hash index of string to be inserted. */
  166.  
  167. int near h_shift;
  168. /* Number of bits by which ins_h must be shifted at each
  169.  * input step. It must be such that after min_match_length steps, the oldest
  170.  * byte no longer takes part in the hash key, that is:
  171.  *   h_shift * min_match_length >= HASH_BITS
  172.  */
  173.  
  174. MATCH *ma_buf = NULL;
  175. /* Buffer used to speed up reading/writing to/from temp file */
  176. #define MA_BUFEND (ma_buf+MA_BUFSIZE)
  177.  
  178. MATCH *ma;
  179. /* Pointer to the most recent match. */
  180.  
  181. int near start_length;
  182. /* Matches not greater than this are discarded. This is used in the lazy match
  183.  * evaluation. If start_length > 1, ma is a valid guess of length start_length
  184.  * and ct_tally has not yet been called.
  185.  */
  186.  
  187.         int near strstart;      /* start of string to insert */
  188.         int near strsize;       /* length of string to insert */
  189.         int near match_length;  /* length of current best match */
  190.         int near bufsize;       /* # of slots in window */
  191.         int near checkpoint;    /* look for new match at this point */
  192. static  int      insert_point;  /* position of next input buffer */
  193.  
  194. static  int      max_lazy_match;
  195. /* We try lazy evaluation only for matches of length 2..max_lazy_match, to
  196.  * speed up the implosion. We use 0 for maximum speed, 0.9*MAX_MATCH_LENGTH
  197.  * for maximum compression.
  198.  */
  199.  
  200.         int near max_chain_length;
  201. /* To speed up implosion, hash chains are truncated to this length.
  202.  * A higher limit improves compression ratio but degrades the speed.
  203.  * We use 40 for maximum speed, 960 for maximum compression. Values
  204.  * below 20 are not recommended.
  205.  */
  206.  
  207. /* Values for max_lazy_match and max_chain_length, depending on the desired
  208.  * pack level (0..9). The values given below have been tuned to exclude
  209.  * worst case performance for pathological files. Better values may be
  210.  * found for specific files. Note that the current algorithm requires 
  211.  * max_lazy >= 2.
  212.  */
  213. typedef struct config {
  214.    int max_lazy;
  215.    int max_chain;
  216. } config;
  217.  
  218. static config configuration_table[10] = {
  219. /* 0 */ {2,                     MAX_MATCH_LENGTH/8}, /* maximum speed */
  220. /* 1 */ {4,                     MAX_MATCH_LENGTH/4},
  221. /* 2 */ {5,                     MAX_MATCH_LENGTH/2},
  222. /* 3 */ {MAX_MATCH_LENGTH/16,   MAX_MATCH_LENGTH/2},
  223. /* 4 */ {MAX_MATCH_LENGTH/16,   3*MAX_MATCH_LENGTH/4},
  224. /* 5 */ {MAX_MATCH_LENGTH/16,   MAX_MATCH_LENGTH},
  225. /* 6 */ {MAX_MATCH_LENGTH/16,   3*MAX_MATCH_LENGTH/2},
  226. /* 7 */ {MAX_MATCH_LENGTH/16,   2*MAX_MATCH_LENGTH},
  227. /* 8 */ {9*MAX_MATCH_LENGTH/10, 2*MAX_MATCH_LENGTH},
  228. /* 9 */ {9*MAX_MATCH_LENGTH/10, 3*MAX_MATCH_LENGTH}}; /* maximum compression */
  229.  
  230.  
  231. #define MIN(a,b) ((a) <= (b) ? (a) : (b))
  232. /* The arguments must not have side effects. */
  233.  
  234. #define EQUAL 0
  235. /* result of strncmp for equal strings */
  236.  
  237. /*  Prototypes for local functions */
  238.  
  239. static void   set_min_match_length OF ((U_CHAR *block, U_INT count));
  240.        ImpErr write_match OF ((IPos ma_start, int ma_length));
  241.        IPos   longest_match OF ((IPos cur_match));
  242.        ImpErr lm_process OF ((U_INT count));
  243.  
  244. /***********************************************************************
  245.  *
  246.  * Initialize the "longest match" routines for a new file.
  247.  * The global variable fd is an implicit parameter.
  248.  */
  249. ImpErr lm_init (pack_level)
  250.     int pack_level; /* 0: best speed, 9: best compression, other: default */
  251. {
  252.     register int i;
  253.  
  254.     /* Validate the arguments */
  255.     bufsize = fd.fd_bufsize;
  256.     strsize = MIN (fd.fd_strsize, MAX_MATCH_LENGTH);
  257.     if (bufsize > WSIZE)          return IM_BADARG;
  258.     if (bufsize < 2 * strsize)    return IM_BADARG;
  259.     if (pack_level < 0 || pack_level > 9) return IM_BADARG;
  260.  
  261.     /* Make sure "bufsize" is a power of 2 */
  262.     if ((bufsize & (bufsize - 1)) != 0) return IM_BADARG;
  263.  
  264.     /* Use dynamic allocation if compiler does not like big static arrays: */
  265. #ifdef DYN_ALLOC
  266.     if (prev == NULL) {
  267.        next = (Hash far*)farmalloc((U_INT)(MAX_DIST+9)*sizeof(Hash));
  268.        prev = (Pos far*) farmalloc((U_INT)(MAX_DIST+HASH_SIZE+9)*sizeof(Pos));
  269.        /* We allocate 16 extra bytes for the normalization under MSDOS */
  270.        if (prev == NULL || next == NULL) return IM_NOMEM;
  271.  
  272. #   if defined(MSDOS) && !defined(OS2)
  273.        /* Normalize to pointers with offset 0 (required by asm version).
  274.         * For OS/2, we can't of course play such nasty games.
  275.         */
  276. #define NORMALIZE(ptr) { \
  277.    *((int*)&ptr+1) += ((unsigned)(ptr-0) + 15) >> 4; \
  278.    *(int*)&ptr = 0; \
  279. }
  280.        NORMALIZE(prev); NORMALIZE(next);
  281. #   endif
  282.     }
  283. #endif /* DYN_ALLOC */
  284.  
  285.     /* Initialize the hash tables. */
  286.     for (i = 0;  i < HASH_SIZE; i++) match_head[i] = NIL;
  287.     for (i = 0;  i <= MAX_DIST; i++) next[i] = NIL;
  288.     /* prev[0..MAX_DIST] will be initialized on the fly */
  289.     ins_h = 0;
  290.  
  291.     /* Assume strsize zeros before the input (bytes beyond strsize
  292.      * can be garbage):
  293.      */
  294.     memset((char*)window, 0, MAX_MATCH_LENGTH);
  295.     /* It is not necessary to duplicate this at the end of the window.
  296.      * Duplication will start only after the first wrap around.
  297.      */
  298.     insert_point = MAX_MATCH_LENGTH;
  299.  
  300.     /* Force a check for the file type (ascii/binary) and set the default
  301.      * configuration parameters:
  302.      */
  303.     min_match_length = 0;
  304.     max_lazy_match   = configuration_table[pack_level].max_lazy;
  305.     max_chain_length = configuration_table[pack_level].max_chain;
  306.  
  307.     /* Do not report matches before the first strsize strings have been
  308.      * inserted in the suffix tree:
  309.      */
  310.     strstart = 0;
  311.     checkpoint = strsize;
  312.     if (ma_buf == NULL) {
  313.         ma_buf = (MATCH *) malloc ((unsigned) (MA_BUFSIZE * sizeof (MATCH)));
  314.         if (ma_buf == NULL) return IM_NOMEM;
  315.     }
  316.     ma = ma_buf - 1;
  317.     start_length = 1;
  318.  
  319.     /* All done. */
  320.     return IM_OK;
  321. }
  322.  
  323. /***********************************************************************
  324.  *
  325.  * Output the match info.
  326.  * IN assertions: The matching strings start at strstart and ma_start
  327.  *    and have a length of ma_length bytes.
  328.  *    If ma_length is not greater than start_length, ma_start is garbage.
  329.  *    strstat == checkpoint. If start_length > 1, ma is the
  330.  *    previous match which has not yet been output.
  331.  * OUT assertion: checkpoint is reset according to the match length
  332.  *    actually chosen.
  333.  *    ma is set to the current match, with start_length set appropriately.
  334.  */
  335. ImpErr write_match(ma_start, ma_length)
  336.     IPos ma_start;           /* start of matched string */
  337.     int ma_length;           /* length of complete match */
  338. {
  339.     int ma_dist = 0;         /* distance of current match */
  340.  
  341.     /* ma_length can be too large towards the end of the input: */
  342.     if (ma_length > strsize) ma_length = strsize;
  343.  
  344. #ifdef DEBUG
  345.     /* check that the match is indeed a match */
  346.     if (ma_length > start_length &&
  347.         strncmp(window + ma_start, window + strstart, ma_length) != EQUAL) {
  348.         fprintf(stderr,
  349.             "write_match: ma_start %d, strstart %d, ma_length %d\n",
  350.             ma_start, strstart, ma_length);
  351.         exit(1);
  352.     }
  353. #endif
  354.     /* PKUNZIP accepts most overlapping matches.  However, when the
  355.      * distance has the value 1, versions of PKUNZIP prior to 1.10 don't
  356.      * handle the overlap properly -- and version 1.10 handles the
  357.      * overlap correctly only if the length is limited to 62 plus the
  358.      * minimum match length; i.e., only if there is no supplementary
  359.      * length byte.  (From phone conversation with Phil Katz, 23 January
  360.      * 1991.) The compression ratio is generally better when we do not
  361.      * limit the match length to 64, so we remove distance-one matches
  362.      * completely. (But PKUNZIP 1.01 also rejects some distance-two matches.
  363.      * This could be fixed but would degrade compression.)
  364.      */
  365.     if (ma_length > 1) {
  366.         ma_dist = strstart - ma_start;
  367.         if (ma_dist < 0) ma_dist += MAX_DIST;
  368.         if (ma_dist == 1) {
  369.             /* keep the previous match if it was delayed */
  370.             if (start_length > 1) {
  371.                 ma_length = 1;
  372.             } else {
  373.                 /* Truncate the match to 1 */
  374.                 ImpErr retcode = write_match(ma_start, 1);
  375.                 if (retcode != IM_OK) return retcode;
  376.  
  377.                 /* Emit a match with a distance of two and a length reduced by
  378.                  * one. This reduced match may be delayed.
  379.                  */
  380.                 checkpoint = ++strstart;
  381.                 retcode = write_match(ma_start, ma_length-1);
  382.                 strstart--;
  383.                 return retcode; /* Leave checkpoint unchanged */
  384.             } /* start_length > 1 */
  385.         } /* ma_dist == 1 */
  386.     } /* ma_length > 1 */
  387.  
  388.     /* If the previous match has been delayed, keep it or prefer the
  389.      * current match:
  390.      */
  391.     if (start_length > 1) {
  392.         /* Keep the previous match if it is not shorter than the current one.
  393.          * Otherwise, emit only the first byte of the previous match,
  394.          * followed by the current match. If we have a delayed match for
  395.          * the last bytes of the input file, the next match will necessarily
  396.          * be smaller, so ct_tally will correctly be called for the delayed
  397.          * match.
  398.          */
  399.         if (start_length >= ma_length) {
  400.             /* Keep the previous match */
  401.             if (start_length == 2) {
  402.                 ma->ma_dist = - ma->ma_dist;
  403.                 ma->l.ma_litc[1] = window[strstart]; /* litc[0] already set */
  404.             } else {
  405.                 ma->l.ma_length = start_length; /* overwrite ma->l.ma_litc */
  406.             }
  407.             checkpoint = strstart + start_length - 1;
  408.             start_length = 1;
  409.             return ct_tally (ma);
  410.         }
  411.         /* Shorten the previous match to zero */
  412.         ma->ma_dist = 0; /* keep ma->l.ma_litc */
  413.         start_length = 1;
  414.         (void) ct_tally (ma); /* ignore result, ct_tally cannot fail */
  415.     }
  416.  
  417.     if (++ma == MA_BUFEND) {
  418.         ma = ma_buf;
  419.         if (twrite ((char *) ma, sizeof(MATCH), MA_BUFSIZE, fd.fd_temp)
  420.             != MA_BUFSIZE) return IM_IOERR;
  421.     }
  422.  
  423.     /* Keep the current match as guess only if its length is small,
  424.      * trying to find a better match at the next step. If speed is not
  425.      * critical, we use this lazy mechanism for all lengths.
  426.      */
  427.     if (ma_length > 1) {
  428.         ma->ma_dist = ma_dist;
  429.         if (ma_length <= max_lazy_match) {
  430.            /* Set ma_litc[0]: this is the only way to identify the unmatched
  431.             * data if the delayed match will be truncated to 1. It is also
  432.             * useful if ma_length == 2: it may be more efficient in this case
  433.             * to encode the individual characters rather than the match info.
  434.             */
  435.             ma->l.ma_litc[0] = window[strstart];
  436.             start_length = ma_length;
  437.             checkpoint = strstart + 1;
  438.             return IM_OK;
  439.         }
  440.         /* At this point, ma_length >= 3, no need for ma_litc */
  441.         ma->l.ma_length = ma_length;
  442.         checkpoint = strstart + ma_length;
  443.     } else {
  444.         ma->ma_dist = 0;
  445.         ma->l.ma_litc[0] = window[strstart]; /* ma_litc[1] is not required */
  446.         checkpoint = strstart + 1;
  447.     }
  448.     return ct_tally (ma);
  449.     /* Keep start_length == 1 */
  450. }
  451.  
  452. /***********************************************************************
  453.  *
  454.  * Determine the minimum match length, based on the type of data
  455.  * in the given input buffer: 2 for binary data, 3 otherwise. Set also
  456.  * h_shift according to the chosen min_match_length, and reduce
  457.  * max_chain_length for binary files.
  458.  *    If the guess about data type is wrong, this only affects the
  459.  * compression ratio and speed but not the correctness of the algorithms.
  460.  * If there are more than 20% bytes which seem non ascii in the first
  461.  * 500 bytes, we assume that the data is binary. (We accept data
  462.  * with a few high bits set as ascii to take into account special
  463.  * word processor formats.)
  464.  */
  465. static void set_min_match_length (block, count)
  466.     U_CHAR *block;          /* input data */
  467.     U_INT  count;           /* # of input char's */
  468. {
  469.     int non_ascii = 0;
  470.     min_match_length = 3;  /* Default ascii */
  471.     if (count >= 500) {
  472.         count = 500;
  473.         while (--count != 0) {
  474.             if (*block <= 6 || *block >= 0x80) non_ascii++;
  475.             block++;
  476.         }
  477.         if (non_ascii > 100) {
  478.             min_match_length = 2;
  479.             max_chain_length >>= 2;
  480.         }
  481.     }
  482.     h_shift = (HASH_BITS+min_match_length-1)/min_match_length;
  483. #ifdef DEBUG
  484.     fprintf(stderr," (min_match_length %d) ", min_match_length);
  485. #endif
  486. }
  487.  
  488. /***********************************************************************
  489.  *
  490.  * Insert string s in the dictionary and set last_match to the previous head
  491.  * of the hash chain (the most recent string with same hash key).
  492.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  493.  *    input characters, so that a running hash key can be computed from the
  494.  *    previous key instead of complete recalculation each time.
  495.  */
  496. #define INSERT_STRING(s, last_match) \
  497. { \
  498.     ins_h = ((ins_h<<h_shift) ^ window[s + min_match_length-1]) & HASH_MASK; \
  499.     prev[s] = last_match = match_head[ins_h]; \
  500.     next[last_match] = prev[next[s] = ins_h + MAX_DIST+1] = s; \
  501. }
  502.     /* next[NIL] is garbage, we can overwrite it if s is a tail */
  503.  
  504. /***********************************************************************
  505.  *
  506.  * Remove string s from the dictionary, or do nothing if s is not yet
  507.  * in the dictionary.
  508.  * IN assertion: s is the tail of its hash chain (the oldest string).
  509.  */
  510. #define DELETE_STRING(s)  {prev[next[s]] = NIL;}
  511. /* No effect if next[s] == NIL (s not in dictionary) */
  512.  
  513. /***********************************************************************
  514.  *
  515.  * Find the longest match starting at the given string. Return its position
  516.  * and set its length in match_length. Matches shorter or equal to
  517.  * start_length are discarded, in which case match_length is unchanged
  518.  * and the result position is NIL.
  519.  * IN assertions: cur_match is the head of the hash chain for the current
  520.  *   string (strstart) and is not NIL, and start_length >= 1
  521.  */
  522. #if !defined(MSDOS) || defined(NO_ASM)
  523. /* For MSDOS, a version of this routine written in assembler is in im_lm.asm.
  524.  * The algorithms are strictly equivalent, so the C version can be used
  525.  * instead if you do not have masm or tasm. (Update the makefile in this case.)
  526.  */
  527. IPos longest_match(cur_match)
  528.     IPos cur_match;
  529. {
  530.     register U_CHAR *match;                   /* pointer in matched string */
  531.     register U_CHAR *scan = window + strstart;/* pointer in current string */
  532.     register int len;                         /* length of current match */
  533.     IPos cur_best = NIL;                      /* best match so far */
  534.     register int ma_length = start_length;    /* best match length so far */
  535.     int chain_count = max_chain_length;       /* used to limit hash chains */
  536.     typedef unsigned short US;
  537.     typedef unsigned long  UL;
  538. #ifdef UNALIGNED_OK
  539.     register US scan_start = *(US*)scan;
  540.     register US scan_end   = *(US*)(scan+ma_length-1);
  541. #else
  542.     register U_CHAR scan_start = *scan;
  543.     register U_CHAR scan_end1  = scan[ma_length-1];
  544.     register U_CHAR scan_end   = scan[ma_length];
  545. #endif
  546.     do {
  547.         match = window + cur_match;
  548.         /* Skip to next match if the match length cannot increase
  549.          * or if the match length is less than 2:
  550.          */
  551. #ifdef UNALIGNED_OK
  552.         /* This code assumes sizeof(unsigned short) == 2 and
  553.          * sizeof(unsigned long) == 4. Do not use UNALIGNED_OK if your
  554.          * compiler uses different sizes.
  555.          */
  556.         if (*(US*)(match+ma_length-1) != scan_end ||
  557.             *(US*)match != scan_start) continue;
  558.  
  559.         len = min_match_length - 4;
  560.         /* If min_match_length == 3, it is not necessary to compare
  561.          * scan[2] and match[2] since they are always equal when the other
  562.          * bytes match, given that the hash keys are equal and that
  563.          * HASH_BITS >= 8.
  564.          */
  565. #       define ML MAX_MATCH_LENGTH
  566.         do {} while ((len+=4) < ML && *(UL*)(scan+len) == *(UL*)(match+len));
  567.  
  568.         if (*(US*)(scan+len) == *(US*)(match+len)) len += 2;
  569.         if (scan[len] == match[len]) len++;
  570.  
  571. #else /* UNALIGNED_OK */
  572.         if (match[ma_length] != scan_end ||
  573.             match[ma_length-1] != scan_end1 || *match != scan_start)
  574.            continue;
  575.         /* It is not necessary to compare scan[1] and match[1] since they
  576.          * are always equal when the other bytes match, given that
  577.          * the hash keys are equal and that h_shift+8 <= HASH_BITS,
  578.          * that is, when the last byte is entirely included in the hash key.
  579.          * The condition is equivalent to
  580.          *       (HASH_BITS+2)/3 + 8 <= HASH_BITS
  581.          * or: HASH_BITS >= 13 (see set_min_match_length()).
  582.          * Also, we check for a match at ma_length-1 to get rid quickly of
  583.          * the match with the suffix of the match made at the previous step,
  584.          * which is known to fail.
  585.          */
  586.         len = 1;
  587.         do {} while (++len < MAX_MATCH_LENGTH && scan[len] == match[len]);
  588.  
  589. #endif /* UNALIGNED_OK */
  590.  
  591.         if (len > ma_length) {
  592.             cur_best = cur_match, ma_length = len;
  593.             if (len >= strsize) break;
  594. #ifdef UNALIGNED_OK
  595.             scan_end = *(US*)(scan+ma_length-1);
  596. #else
  597.             scan_end1  = scan[ma_length-1];
  598.             scan_end   = scan[ma_length];
  599. #endif
  600.         }
  601.     } while (--chain_count != 0 && (cur_match = prev[cur_match]) != NIL);
  602.  
  603.     if (ma_length > start_length) match_length = ma_length;
  604.     return cur_best;
  605. }
  606. #endif /* MSDOS */
  607.  
  608. /***********************************************************************
  609.  *
  610.  * Process a block of input characters, generating zero or more match
  611.  * info records as appropriate.
  612.  * IN assertion: count <= BSZ
  613.  */
  614. ImpErr lm_input (block, count)
  615.     U_CHAR *block;          /* input data */
  616.     U_INT  count;           /* # of input char's */
  617. {
  618.     if (count == 0) return IM_OK;
  619.  
  620.     /* Determine the input file type if this is the first call */
  621.     if (min_match_length == 0) set_min_match_length (block, count);
  622.  
  623.     if (insert_point + count <= sizeof(window)) {
  624.         memcpy((char*)window + insert_point, (char*)block, count);
  625.  
  626.     } else {
  627.         int remain = sizeof(window)-insert_point;
  628.         memcpy((char*)window + insert_point, (char*)block, remain);
  629.  
  630.         memcpy((char*)window + MAX_MATCH_LENGTH,
  631.                (char*)block + remain, count - remain);
  632.     }
  633.     insert_point += count;
  634.     if (insert_point > MAX_DIST) {
  635.         /* Duplicate the end of the window */
  636.         memcpy((char*)window,
  637.                (char*)window + MAX_DIST,
  638.                MIN (insert_point - MAX_DIST, MAX_MATCH_LENGTH));
  639.     }
  640.     if (insert_point >= sizeof(window)) insert_point -= MAX_DIST;
  641.  
  642.     return lm_process(count);
  643. }
  644.  
  645. /***********************************************************************
  646.  *
  647.  * Process a block of characters already inserted in the window
  648.  * IN assertion: count > 0
  649.  */
  650. #if !defined(MSDOS) || defined(NO_ASM)
  651. ImpErr lm_process (count)
  652.     U_INT  count;           /* number of bytes to process */
  653. {
  654.     ImpErr retcode;         /* as usual */
  655.     IPos cur_match;         /* starting point for longest match search */
  656.     IPos best_match = NIL;  /* longest match found */
  657.     int delete_point;       /* position of next string to remove */
  658.     
  659.     delete_point = strstart - bufsize + MAX_MATCH_LENGTH - 1;
  660.     if (delete_point < 0) delete_point += MAX_DIST;
  661.  
  662.     /* Process the input block. */
  663.     do {
  664.         /* Insert the string window[strstart .. strstart+strsize-1] in the
  665.          * dictionary, and set cur_match to the head of the hash chain:
  666.          */
  667.         INSERT_STRING(strstart, cur_match);
  668.  
  669.         if (strstart == checkpoint) {
  670.             /* Find the longest match, discarding those <= start_length */
  671.             match_length = 0;
  672.             if (cur_match != NIL) {
  673.                 best_match = longest_match (cur_match);
  674.                 /* longest_match updates match_length if longer match found */
  675.             }
  676.             retcode = write_match (best_match, match_length);
  677.             if (retcode != IM_OK) return retcode;
  678.         }
  679.  
  680.         /* Remove the oldest string from the dictionary, except if we have not
  681.          * yet created bufsize dictionary entries. We could avoid this
  682.          * deletion and check instead for obsolete pointers in
  683.          * longest_match(), but this would be slower.
  684.          */
  685. #if (MAX_DIST & (MAX_DIST-1)) != 0
  686.         if (++delete_point == MAX_DIST) delete_point = 0;
  687. #else
  688.         delete_point = (delete_point + 1) & (MAX_DIST-1);
  689. #endif
  690.         DELETE_STRING (delete_point);
  691.  
  692.         if (++strstart == MAX_DIST) {
  693.             strstart = 0, checkpoint -= MAX_DIST;
  694.         }
  695.     } while (--count != 0);
  696.     return IM_OK;
  697. }
  698. #endif /* MSDOS */
  699.  
  700. /***********************************************************************
  701.  *
  702.  * Wind up processing by flushing unprocessed input. For normal processing,
  703.  * this routine is called twice (by imp_size then imp_clear) and the
  704.  * second call does nothing. In case of error, this routine is called only
  705.  * by imp_clear().
  706.  */
  707. ImpErr lm_windup()
  708. {
  709.     ImpErr retcode;
  710.     int matches;
  711.  
  712.     /* Process the remaining input. */
  713.     while (strsize > 0) {
  714.        retcode = lm_process (1);
  715.        if (retcode != IM_OK) return retcode;
  716.        --strsize;
  717.     }
  718.     /* Flush the match buffer. */
  719.     if ((matches = ma-ma_buf+1) != 0 && matches != 
  720.         twrite ((char *) ma_buf, sizeof(MATCH), matches, fd.fd_temp)) {
  721.         return IM_IOERR;
  722.     }
  723.     ma = ma_buf - 1;
  724.     return IM_OK;
  725. }
  726.